package com.xlhj.boot.config;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: caijliu
 * @description: CuratorConfig
 * @data: 21/08/2021 17:24
 */
@Configuration
public class CuratorConfig {

    @Value("${zookeeper.connect.address}")
    private String connectStr;
    @Value("${zookeeper.connect.connection-time-out}")
    private int connectionTimeout;
    @Value("${zookeeper.connect.session-time-out}")
    private int sessionTimeout;
    @Value("${zookeeper.connect.sleep-time-out}")
    private int sleepTimeOut;
    @Value("${zookeeper.connect.max-retries}")
    private int maxRetries;
    @Value("${zookeeper.connect.name-space}")
    private String namespace;

    /**
     * 初始化curator客户端
     * @return
     */
    @Bean
    public CuratorFramework getCuratorClient() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(sleepTimeOut, maxRetries);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(connectStr)
                .connectionTimeoutMs(connectionTimeout)
                .sessionTimeoutMs(sessionTimeout)
                .namespace(namespace)
                .retryPolicy(retryPolicy).build();
        client.start();
        return client;
        /*RetryPolicy retryPolicy = new ExponentialBackoffRetry(sleepTimeOut, maxRetries);
        CuratorFramework client = CuratorFrameworkFactory.newClient(connectStr, retryPolicy);
        client.start();
        return client;*/
    }
}
